package org.insia.smartposse.mapping.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.insia.smartposse.manager.ProjectsListManager;
import org.insia.smartposse.mapping.Projects;
import org.insia.smartposse.mapping.base.BaseProjectsDAO;

public class ProjectsDAO
extends BaseProjectsDAO
implements org.insia.smartposse.mapping.dao.iface.ProjectsDAO
{

	public ProjectsDAO() {
	}

	public ProjectsDAO(Session session) {
		super(session);
	}

	private Criteria critAll(Session session) {
		Criteria crit = session.createCriteria(getReferenceClass());
		if (null != getDefaultOrder())
			crit.addOrder(getDefaultOrder());
		return crit;
	}

	/**
	 * Return the number of Job Remain for this Project
	 *
	 * @param _project
	 */
	public Integer getNbJobRemain(Projects _project) {
		return (Integer) critAll(getSession()).add(
			Restrictions.eq("Id", _project.getId())).createCriteria(
			"JobProjectList").add(Restrictions.isNull("Freelance")).list()
			.size();
	}

	/**
	 * Method for obtains list of Project with several information :
	 * <ul>
	 * <li>Complete: if the Project is complete or not</li>
	 * <li>Subject: word contains in Subject of Project</li>
	 * </ul>
	 *
	 * @param session
	 * @param complete
	 * @param subject
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Projects> search(Session session, int complete, String subject,
		String shortDescription) {

		Criteria crit = critAll(session);

		// Complete or Not
		if (complete == ProjectsListManager.COMPLETE) {
			crit.add(Expression.eq("Complete", true));
		}

		if (complete == ProjectsListManager.NOTCOMPLETE) {
			crit.add(Expression.eq("Complete", false));
		}

		// Search with subject
		if (null != subject) {
			crit.add(Restrictions.like("Subject", "%" + subject + "%"));
		}

		if (null != shortDescription){
			crit.add(Restrictions.like("ShortDescription", "%" + shortDescription + "%"));
		}

		return crit.list();
	}

}